import tokenizer from './core/tokenizer'
import parser from './core/parser/index'
import formatter from './core/formatter'
import condGenerator from './core/condition-generator'
import type { Ast, Token } from '../../types/retrieval-sql'
import type { PatentIdentifier } from '@/types'
import transformer from './core/transformer/index'
import { expendIdentifiers } from './core/config'

export function resolveAst(identifiers: PatentIdentifier[], input: string | Token[]) {
  let tokens
  if (typeof input === 'string') {
    tokens = tokenizer(input)
  } else {
    tokens = input
  }
  const ast = parser(tokens)
  return ast ? transformer(ast, [...identifiers, ...(expendIdentifiers as any)]) : null
}

export function conditionGenerator(identifiers: PatentIdentifier[], input: string | Ast | Token[]): Ast | null {
  if (typeof input === 'string' || Array.isArray(input)) {
    const ast = resolveAst(identifiers, input)
    if (!ast) {
      return null
    }
    return condGenerator(ast)
  }
  return condGenerator(input as Ast)
}

export function prettier(identifiers: PatentIdentifier[], input: string | Ast) {
  let ast
  if (typeof input === 'string') {
    ast = resolveAst(identifiers, input)
  } else {
    ast = input
  }
  return ast ? formatter(ast) : ''
}
